import 'dart:convert';
import 'dart:io';
import 'package:flutter_logger_server/utils/log_utils.dart';
import 'package:flutter_logger_server/beans/websocket_bean.dart';
import 'package:shelf_web_socket/shelf_web_socket.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;

import '../flutter_logger_server.dart';

class WebSocketUtils {
  HttpServer? _webSocketServer;
  final List<WebSocketChannel> _webSocketChannels = [];

  init() async {
    _webSocketServer = await shelf_io.serve(webSocketHandler((WebSocketChannel webSocket) {
      _webSocketChannels.add(webSocket);
      webSocket.sink.add("hello");
      webSocket.stream.listen((message) {
        LogUtils.log("receive message: $message");
        webSocket.sink.add("echo $message");
      },onDone: (){
        LogUtils.log("done");
        _webSocketChannels.remove(webSocket);
      },onError: (error){
        LogUtils.log("error: $error");
      });
    }), InternetAddress.anyIPv4, 9998);
    //ios ws://127.0.0.1:9998/SMWdhRwrlhQ=/ws
    LogUtils.log('Serving at ws://${_webSocketServer?.address.host}:${_webSocketServer?.port}\n');
    FlutterLoggerServer.instance.webSocketUrl = 'ws://${_webSocketServer?.address.host}:${_webSocketServer?.port}';
  }

  close() {
    _webSocketServer?.close();
  }

  postMessage(String type, String message) {
    LogUtils.log("_webSocketChannels：${_webSocketChannels.length}");
    // debugPrint("postMessage:$type  $message");
    for (var element in _webSocketChannels) {
      try {
        element.sink.add(jsonEncode(WebSocketBean(type, message)));
      } catch (e) {
        LogUtils.log(e.toString());
      }
    }
  }
}
